/* eslint-disable no-nested-ternary */
/* eslint-disable import/prefer-default-export */
import { Input, Typography, Form } from 'antd';
import get from 'lodash/get';
import React from 'react';

const { Text } = Typography;

export const EditableContext = React.createContext();

export class EditableCell extends React.Component {
  renderCell = form => {
    const { getFieldDecorator } = form;
    const {
      editing,
      dataIndex,
      title,
      record,
      index,
      children,
      handleSaveRow,
      copyable,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              initialValue: record[dataIndex],
              rules: [
                {
                  required: true,
                  message: `${title}不能为空！`,
                },
              ],
            })(
              <Input
                placeholder={`请输入${title}...`}
                onPressEnter={() => handleSaveRow(form, record.endpointId)}
                allowClear
              />
            )}
          </Form.Item>
        ) : copyable ? (
          <Text copyable={{ text: get(children, '[2]') }}>{children}</Text>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}
